package com.zjny.util;

import javax.servlet.http.HttpServletRequest;

/**
 * packageName com.zjny.util
 * ip配置类
 *
 * @author cui haida
 * @version JDK 8
 * 2025/6/18
 */
public class IpUtils {
    public static String getRemoteIp(HttpServletRequest request) {
        // 从请求头中拿到X-Forwarded-For, 尝试获取IP
        String ip = request.getHeader("X-Forwarded-For");
        // 如果没有拿到，则从请求头中拿到X-Real-IP
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(",");
        // 如果存在多个ip，则取第一个ip，并且去掉ipv6的表示方式，转成ipv4
        return ips[0].trim().replace("0:0:0:0:0:0:0:1", "127.0.0.1");
    }
}